package com.laogao.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laogao.dto.ExamDto;
import com.laogao.entity.Exam;
import com.laogao.entity.Question;
import com.laogao.entity.SelectOptions;
import com.laogao.mapper.ExamMapper;
import com.laogao.service.ExamService;
import com.laogao.service.OptionService;
import com.laogao.service.QuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@RequiredArgsConstructor
@Primary
public class ExamServiceImpl2 extends ServiceImpl<ExamMapper, Exam> implements ExamService {

    private final ExamMapper examMapper;
    private final QuestionService questionService;
    private final OptionService optionService;

    @Transactional(rollbackFor = Exception.class)
    public void saveExamWithAll(ExamDto examDto, int questionCount, int OptionsCountPerQuestion) {
        // 预先生成试卷 ID
        Exam exam = new Exam();
        String examId = IdUtil.getSnowflakeNextIdStr();
        exam.setId(examId);
        exam.setName(examDto.getName());
        examMapper.insert(exam);

        //1000个问题
        List<Question> questions = examDto.getQuestions();
        //选项
        List<SelectOptions> selectOptions = new ArrayList<>();
        for (Question question : questions) {
            selectOptions.addAll(question.getSelectOptionsList());
        }

        int BATCH_SIZE = 1000;
        // 将题目列表拆分成多个批次
        List<List<Question>> questionBatches = ListUtil.partition(questions, BATCH_SIZE);
        List<List<SelectOptions>> optionBatches = ListUtil.partition(selectOptions, BATCH_SIZE);

        List<CompletableFuture<Void>> futures = new ArrayList<>();

        // 异步批量插入题目
        for (List<Question> batch : questionBatches) {
            CompletableFuture<Void> future = questionService.saveBatchAsync(batch);
            futures.add(future);
        }

        // 异步批量插入选项
        for (List<SelectOptions> batch : optionBatches) {
            CompletableFuture<Void> future = optionService.saveBatchAsync(batch);
            futures.add(future);
        }

        // 等待所有异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }
}